﻿using EYangFramework.Common.Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EYangFramework.Common.Timer
{
    [AutoBind]
    public class InstanceTimer:IInstanceTimer
    {
        public EventHandler Event { get; set; }
        public bool isRunning = false;
        private System.Threading.Timer Timer;
        private int Period = 0;
        public InstanceTimer()
        {
            Timer = new System.Threading.Timer(Elapsed, null, Timeout.Infinite, Timeout.Infinite);
        }
        private void Elapsed(object state)
        {
            //因为定时器是自动调用的,所以不能传入参数
            Timer.Change(Timeout.Infinite, Timeout.Infinite);
            Event?.Invoke(null, null);
            Timer.Change(Period * 1000, Timeout.Infinite);
        }

        public void Start(int period)
        {
            //throw new NotImplementedException();
            if (!isRunning)
            {
                isRunning = true;
                Period = period;
                Timer.Change(period * 1000, Timeout.Infinite);
            }
        }

        public void Stop()
        {
            //throw new NotImplementedException();
            if (isRunning)
            {
                isRunning = false;
                Timer.Change(Timeout.Infinite, Timeout.Infinite);
            }
        }
        
    }
}
